/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package be.msec.client.connection;

/**
 *
 * @author Jorn
 */

import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

import be.msec.client.utils.ArrayUtils;

import com.sun.javacard.apduio.Apdu;
import com.sun.javacard.apduio.CadClient;
import javax.smartcardio.CommandAPDU;
import javax.smartcardio.ResponseAPDU;



public class SimulatedConnection implements IConnection {
	private CadClient cad;
	private Socket sock;
	private int port;

	public SimulatedConnection(){
		port=9025;
	}

	public void setPort(int i){
		port=i;
	}

	public void connect() throws Exception {
		sock = new Socket("localhost", port);
		InputStream is = sock.getInputStream();
		OutputStream os = sock.getOutputStream();
		cad = new CadClient(is,os);
                cad.powerUp();
	}
        public void close() throws Exception {
            cad.powerDown();
            sock.close();
            cad.close();
        }
	public ResponseAPDU transmit(CommandAPDU apdu) throws Exception {
            Apdu a = new Apdu();
            a.command[0] = (byte)apdu.getCLA();
            a.command[1] = (byte)apdu.getINS();
            a.command[2] = (byte)apdu.getP1();
            a.command[3] = (byte)apdu.getP2();
            a.setDataIn(apdu.getData());
            a.Le = apdu.getNe();
            cad.exchangeApdu(a);
            int le = a.getLe();
			byte[] respBytes = a.getResponseApduBytes();
            return new ResponseAPDU(ArrayUtils.getSubArray(respBytes,respBytes.length-le-2,le+2));
	}

}

